package part1.chapter5_refactoring;

/**
 * Created by lie on 2018/3/8.
 * 得到一个不大于N的素数数组
 * 思路是排除掉a*a,a*(a+1)...的所有乘积，
 * 然后再排除(a+1)*(a+1),(a+1)*(a+1+1)的乘积
 */
public class PrimeGenerator1 {

    protected static int[] result;
    protected static boolean[] isCrossed;


    //按照思路列个方法
    public static int[] getPrimes(int maxValue){
        if (maxValue <= 2) {
            return new int[0];
        }else {
            //1 初始化
            init(maxValue);
            //2 排除掉非素数
            filtration();
            //3 返回
            putIsCrossedIntoResults();
            return result;
        }
    }

    protected static void putIsCrossedIntoResults() {
        result = new int[countIsCrossed()];
        for (int j=0,i=2;i<isCrossed.length;i++){
            if (isCrossed[i]){
                result[j++] = i;
            }
        }

    }

    protected static int countIsCrossed() {
        int count = 0;
        for (int i =2;i<isCrossed.length;i++){
            if (isCrossed[i]){
                count++;
            }
        }
        return count;
    }

    private static void filtration() {

        for (int i=2;i< isCrossed.length;i++){
            if (isCrossed[i]){
                for (int multiple = i; multiple*i < isCrossed.length;multiple++){
                    isCrossed[i * multiple] = false;
                }
            }
        }

    }

    protected static void init(int maxValue) {
        isCrossed = new boolean[maxValue + 1];
        for (int i=2; i< isCrossed.length; i++){
            isCrossed[i] = true;
        }
    }

}
